package com.yundasys.lab03springbootshardingjdbc.algorithm;

import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @PACKAGE_NAME: com.yundasys.lab03springbootshardingjdbc.algorithm
 * @NAME: HitAlgorithm
 * @USER: jiangta
 * @DATE: 2022/9/30
 * @TIME: 3:30 下午
 * @PROJECT_NAME: springboot-labs
 */
public class HitAlgorithm implements HintShardingAlgorithm<Long> {

    /**
     * Sharding.
     *
     * <p>sharding value injected by hint, not in SQL.</p>
     *
     * @param availableTargetNames available data sources or tables's names
     * @param shardingValue sharding value
     * @return sharding result for data sources or tables's names
     */
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<Long> shardingValue) {
        Collection<String> result = new ArrayList<>();
        for (String each : availableTargetNames) {
            for (Long value : shardingValue.getValues()) {
                if (each.endsWith(String.valueOf(value % 2))) {
                    result.add(each);
                }
            }
        }
        return result;
    }
}
